<template>
  <view class="container">
    <!-- 顶部背景区域 -->
    <view class="search-area">
      <!-- 状态栏占位 -->
      <view class="status-bar" :style="{ height: `${systemInfo?.statusBarHeight}px` }" />

      <!-- 搜索栏 -->
      <view class="header">
        <view class="search-bar" :style="searchBarStyle" @click="goToSearch">
          <wd-search v-model="searchValue" placeholder="搜索商品" background="#f7f8fa" readonly disabled use-action-slot />
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <swiper class="banner" circular :indicator-dots="true" :autoplay="true" interval="3000" duration="1000">
        <swiper-item v-for="(item, index) in bannerList" :key="index" class="banner-item">
          <image :src="item" mode="aspectFill" class="banner-image" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 精选分类 -->
    <view class="category-section">
      <view class="section-header">
        <view class="section-title">
          <view class="title-bar"></view>
          <text>精选分类</text>
        </view>
        <view class="more-link" @click="navigateToGoodsList()">
          更多 <wd-icon name="arrow-right" size="14" />
        </view>
      </view>
      <scroll-view scroll-x class="category-scroll" show-scrollbar="false">
        <view class="category-list">
          <template v-if="!loading">
            <view class="category-item" v-for="item in categories" :key="item.id" @click="navigateToCategory(item)">
              <image :src="item.image" mode="aspectFill" class="category-image" />
              <view class="category-name">{{ item.name }}</view>
            </view>
          </template>
          <template v-else>
            <view class="category-item" v-for="i in 5" :key="i">
              <view class="skeleton-image"></view>
              <view class="skeleton-text"></view>
            </view>
          </template>
        </view>
      </scroll-view>
    </view>

    <!-- 品牌精选 -->
    <view class="brand-section">
      <view class="section-header">
        <view class="section-title">
          <view class="title-bar"></view>
          <text>品牌精选</text>
        </view>
        <view class="more-link" @click="navigateToGoodsList()">
          更多 <wd-icon name="arrow-right" size="14" />
        </view>
      </view>
      <scroll-view scroll-x class="brand-scroll" show-scrollbar="false">
        <view class="brand-list">
          <view v-for="brand in brandList" :key="brand.id" class="brand-item" @click="navigateToBrand(brand)">
            <image :src="brand.logoUrl" mode="aspectFit" class="brand-logo" />
            <text class="brand-name">{{ brand.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 商品列表 -->
    <view class="product-section">
      <view class="section-header">
        <view class="section-title">
          <view class="title-bar"></view>
          <text>推荐商品</text>
        </view>
        <view class="more-link" @click="navigateToGoodsList()">
          更多 <wd-icon name="arrow-right" size="14" />
        </view>
      </view>

      <view class="product-grid">
        <template v-if="!loading">
          <view class="product-item" v-for="item in products" :key="item.id" @click="navigateToDetail(item)">
            <image :src="item.mainImageUrl" mode="aspectFill" class="product-image" />
            <view class="product-info">
              <text class="product-name">{{ item.name }}</text>

              <view class="product-meta">
                <view class="tags-wrapper">
                  <text class="brand-tag">{{ item.brandName }}</text>
                  <text class="category-tag">{{ item.categoryName }}</text>
                </view>

                <view class="price-wrapper">
                  <view class="current-price">
                    <text class="price-symbol">¥</text>
                    <text class="price-value">{{ item.price }}</text>
                  </view>
                  <text class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</text>
                </view>

                <text class="sales-info">已售 {{ item.salesCount }}</text>
              </view>
            </view>
          </view>
        </template>
        <template v-else>
          <view class="product-item skeleton" v-for="i in 4" :key="i">
            <view class="skeleton-image"></view>
            <view class="skeleton-content">
              <view class="skeleton-text"></view>
              <view class="skeleton-text"></view>
            </view>
          </view>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getBannerList, getBrandList, getRecommendProducts } from '@/api/home.js'
import { getSelectedCategories } from '@/api/category.js'
import { getSystemInfo } from '@/utils/system'

// 搜索相关
const searchValue = ref('')

// 轮播图数据
const bannerList = ref([])
// 品牌列表数据
const brandList = ref([])
// 精选分类数据
const categories = ref([])

// 商品数据
const products = ref([])

// 新增状态
const loading = ref(true)

// 系统信息
const systemInfo = ref(null)

// 获取系统信息
onMounted(() => {
  systemInfo.value = getSystemInfo()
})

// 计算搜索栏样式
const searchBarStyle = computed(() => {
  if (!systemInfo.value?.menuButtonRect) return {}

  const { menuButtonRect } = systemInfo.value
  return {
    position: 'fixed',
    top: `${menuButtonRect.top}px`,
    left: '24rpx',
    height: `${menuButtonRect.height}px`,
    width: `${menuButtonRect.left - 24}px`,
    zIndex: 100
  }
})

// 跳转到搜索页面
const goToSearch = () => {
  uni.navigateTo({
    url: '/pages/search/index'
  })
}

// 下拉刷新
const onPullDownRefresh = async () => {
  try {
    await Promise.all([
      loadBannerList(),
      loadBrandList(),
      loadSelectedCategories(),
      loadMoreProducts()
    ])
  } catch (err) {
    console.error('刷新数据失败：', err)
  } finally {
    uni.stopPullDownRefresh()
  }
}

// 修改加载商品的函数
const loadMoreProducts = async () => {
  try {
    const res = await getRecommendProducts()
    if (res && res.length) {
      products.value = res
    }
  } catch (err) {
    console.error('加载商品失败：', err)
    uni.showToast({
      title: '加载商品失败',
      icon: 'none'
    })
  }
}

// 获取轮播图数据
const loadBannerList = async () => {
  try {
    const res = await getBannerList()
    bannerList.value = res || []
  } catch (err) {
    console.error('获取轮播图失败：', err)
  }
}

// 获取品牌列表
const loadBrandList = async () => {
  try {
    const res = await getBrandList()
    brandList.value = res || []
  } catch (err) {
    console.error('获取品牌列表失败：', err)
  }
}

// 获取精选分类
const loadSelectedCategories = async () => {
  try {
    const res = await getSelectedCategories()
    categories.value = res || []
  } catch (err) {
    console.error('获取精选分类失败：', err)
    categories.value = []
  }
}

// 跳转到商品列表
const navigateToGoodsList = () => {
  uni.navigateTo({
    url: '/pages/goods/list'
  })
}

// 跳转到分类详情
const navigateToCategory = (category) => {
  uni.navigateTo({
    url: `/pages/goods/list?categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}`
  })
}

// 跳转到商品详情页
const navigateToDetail = (product) => {
  if (!product || !product.id) {
    uni.showToast({
      title: '商品信息不完整',
      icon: 'none'
    })
    return
  }

  // 使用 uni.navigateTo 跳转到商品详情页
  uni.navigateTo({
    url: `/pages/product/detail?id=${product.id}`,
    fail: () => {
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到品牌页面
const navigateToBrand = (brand) => {
  uni.navigateTo({
    url: `/pages/goods/list?brandId=${brand.id}&brandName=${encodeURIComponent(brand.name)}`
  })
}

// 修改 onMounted，初始化时也要加载商品数据
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadBannerList(),
      loadBrandList(),
      loadSelectedCategories(),
      loadMoreProducts() // 添加商品数据的初始加载
    ])
  } catch (err) {
    console.error('初始化数据失败：', err)
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.search-area {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 100;
}

.status-bar {
  width: 100%;
  background: #fff;
}

.header {
  position: relative;
  background: #fff;
  padding-top: v-bind('(systemInfo?.menuButtonRect?.height || 0) + (systemInfo?.menuButtonRect?.top || 0) - (systemInfo?.statusBarHeight || 0) + "px"');
  padding-bottom: 20rpx;
}

.search-bar {
  background: #fff;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  width: 100%;

  :deep(.wd-search) {
    flex: 1;
    height: 100%;
    background: #fff;

    .wd-search__inner {
      height: 100%;
      display: flex;
      align-items: center;
      border-radius: 32rpx;
      background: #f7f8fa;
      padding: 0 24rpx;
    }

    .wd-search__input {
      font-size: 28rpx;
      pointer-events: none;
      background: #f7f8fa;
    }

    .wd-search__cancel {
      display: none;
    }
  }
}

.banner-section {
  margin-top: v-bind('(systemInfo?.menuButtonRect?.height || 0) + (systemInfo?.menuButtonRect?.top || 0) + 48 + "px"');
  margin-left: 30rpx;
  margin-right: 30rpx;
}

.banner {
  height: 300rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.banner-item {
  width: 100%;
  height: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
}

// 广告横幅样式
.ad-banner {
  margin: 30rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
}

.ad-image {
  width: 100%;
  height: 180rpx;
  transform: scale(1.01);
}

// 品牌精选样式
.brand-section {
  margin: 30rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.brand-scroll {
  width: 100%;
  margin-top: 20rpx;
}

.brand-list {
  display: flex;
  white-space: nowrap;
}

.brand-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40rpx;
  width: 140rpx;

  &:last-child {
    margin-right: 0;
  }
}

.brand-logo {
  width: 100rpx;
  height: 100rpx;
  margin-bottom: 12rpx;
  border-radius: 50%;
  background-color: #f8f8f8;
}

.brand-name {
  font-size: 26rpx;
  color: #333;
  text-align: center;
}

// 优化现有样式
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;

  .title-bar {
    width: 6rpx;
    height: 32rpx;
    background-color: #FF6B6B;
    margin-right: 16rpx;
    border-radius: 4rpx;
  }

  text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.more-link {
  font-size: 26rpx;
  color: #999;
  display: flex;
  align-items: center;
  padding: 10rpx 0 10rpx 20rpx;

  .wd-icon {
    margin-left: 4rpx;
  }
}

.product-section {
  margin: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  padding: 0 2rpx;
}

.product-item {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  position: relative;

  &:active {
    transform: scale(0.98);
  }

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.02);
    opacity: 0;
    transition: opacity 0.2s;
  }

  &:active::after {
    opacity: 1;
  }
}

.product-image {
  width: 100%;
  height: 280rpx;
  object-fit: cover;
  background-color: #fafafa;
  vertical-align: middle;
}

.product-info {
  padding: 12rpx;
}

.product-name {
  font-size: 26rpx;
  color: #333;
  line-height: 1.4;
  height: 72rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.product-meta {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.tags-wrapper {
  display: flex;
  gap: 6rpx;
  flex-wrap: wrap;
}

.brand-tag,
.category-tag {
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  max-width: 110rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.brand-tag {
  color: #ff6b6b;
  background-color: rgba(255, 107, 107, 0.06);
}

.category-tag {
  color: #5c7cfa;
  background-color: rgba(92, 124, 250, 0.06);
}

.price-wrapper {
  display: flex;
  align-items: baseline;
  gap: 6rpx;
  margin-top: 2rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 20rpx;
  color: #ff4444;
  font-weight: bold;
}

.price-value {
  font-size: 30rpx;
  color: #ff4444;
  font-weight: bold;
}

.original-price {
  font-size: 20rpx;
  color: #999;
  text-decoration: line-through;
}

.sales-info {
  font-size: 20rpx;
  color: #999;
}

// 精选分类样式
.category-section {
  margin: 30rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.category-scroll {
  width: 100%;
  margin-top: 20rpx;
}

.category-list {
  display: flex;
  white-space: nowrap;
  padding: 10rpx 0;
}

.category-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-right: 30rpx;
  width: 140rpx;

  &:last-child {
    margin-right: 0;
  }

  &:active {
    transform: scale(0.95);
  }
}

.category-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-bottom: 16rpx;
  background-color: #f7f8fa;
}

.category-name {
  font-size: 26rpx;
  color: #333;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.category-empty {
  width: 100%;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 修改滚动条样式
.category-scroll ::-webkit-scrollbar {
  display: none;
}

// 新增骨架屏样式
.skeleton-image {
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
  background-size: 400% 100%;
  animation: skeleton-loading 1.4s ease infinite;
  border-radius: 50%;
}

.skeleton-text {
  height: 32rpx;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
  background-size: 400% 100%;
  animation: skeleton-loading 1.4s ease infinite;
  border-radius: 4rpx;
  margin-top: 16rpx;
}

.skeleton-content {
  padding: 20rpx;

  .skeleton-text {
    margin-top: 12rpx;

    &:first-child {
      width: 60%;
    }

    &:last-child {
      width: 40%;
    }
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0 50%;
  }
}

// 优化骨架屏样式
.skeleton {
  .skeleton-image {
    height: 280rpx;
  }

  .skeleton-content {
    padding: 12rpx;

    .skeleton-text {
      height: 28rpx;
      margin: 8rpx 0;
      background: linear-gradient(90deg, #f5f5f5 25%, #efefef 37%, #f5f5f5 63%);
      background-size: 400% 100%;
      animation: skeleton-loading 1.4s ease infinite;
      border-radius: 4rpx;

      &:first-child {
        width: 80%;
      }

      &:last-child {
        width: 60%;
      }
    }
  }
}
</style>